import { removeToken, setToken } from "../../utils/storage";
import { loginByUsername, logoutAPI } from "../../service/user";

const state = {
  token: "",
  userInfo: {}
};
const getters = {};
const mutations = {
  SET_TOKEN: (state, token) => {
    setToken(token);
    state.token = token;
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
  }
};
const actions = {
  LoginByUsername({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginByUsername({
        username: userInfo.username,
        password: userInfo.password,
        captcha: userInfo.captcha
      }).then(res => {
        const data = res.data;
        commit("SET_TOKEN", data.token);
        commit("SET_USER_INFO", data);
        resolve(data);
      }).catch(error => {
        reject(error);
      });
    });
  },
  FedLogOut({ commit }) {
    return new Promise((resolve, reject) => {
      logoutAPI().then(res => {
        commit("SET_TOKEN", "");
        removeToken();
        commit("SET_USER_INFO", {});
        resolve();
      }).catch(() => {
        commit("SET_TOKEN", "");
        commit("SET_USER_INFO", {});
        removeToken();
        reject();
      });
    });
  }
};
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
};
